<script setup>
	import { nextTick, ref, watch } from 'vue'
	import { message } from 'ant-design-vue'
	import { SendOutlined, SettingOutlined } from '@ant-design/icons-vue'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'
	import { useApiDatasetStore } from '@/views/plugin/dashboard/store/apiDataset'

	import ApiDebugParameterForm from './ApiDebugParameterForm.vue'
	import ApiResponseViewer from './ApiResponseViewer.vue'
	import ApiSaveActions from './ApiSaveActions.vue'

	const emit = defineEmits(['change', 'loadData'])
	const store = useApiDatasetStore()

	// 组件状态
	const loading = ref(false)
	const responseData = ref(null)
	const responseTime = ref(0)
	const responseSize = ref(0)
	const apiList = ref([])
	const showParamsPanel = ref(true)
	const apiSaveActionsRef = ref()

	// 打开调试器
	const onOpen = (record) => {
		if (record) {
			store.setFormData(record)
			nextTick(() => {
				loadApiList()
			})
		}
	}

	// 发送请求
	const sendRequest = async () => {
		if (!store.formData.itemConfig.apiPath) {
			message.warning('请先选择API接口')
			return
		}

		try {
			loading.value = true
			const startTime = Date.now()

			// 构建请求配置
			const requestConfig = {
				type: store.connectorInfo?.type || 'LOCAL_API',
				config: {
					...store.connectorInfo?.config,
					apiPath: store.formData.itemConfig.apiPath,
					method: 'GET'
				},
				params: store.formData.itemConfig.apiParams || {}
			}

			const res = await dataConnectorApi.previewData(requestConfig)
			responseData.value = res
			responseTime.value = Date.now() - startTime
			responseSize.value = JSON.stringify(res).length

			// 触发变更事件
			emit('change', res)

			message.success(`请求成功，耗时 ${responseTime.value}ms`)
		} catch (error) {
			console.error('请求失败:', error)
			responseData.value = {
				error: true,
				message: error.message || '请求失败',
				details: error
			}
			message.error('请求失败：' + (error.message || '未知错误'))
		} finally {
			loading.value = false
		}
	}

	// 获取API接口列表
	const loadApiList = async () => {
		try {
			if (!store.formData.dataConnectorId) {
				return
			}

			// 先获取连接器信息
			const connectorList = await dataConnectorApi.list({ id: store.formData.dataConnectorId })
			if (connectorList && connectorList.length > 0) {
				const connectorInfo = connectorList[0]
				store.setConnectorInfo(connectorInfo)

				// 检查连接器类型是否支持API接口查询
				const supportedTypes = ['LOCAL_API', 'EXTERNAL_API', 'HTTP']
				if (!supportedTypes.includes(connectorInfo.type)) {
					console.warn(`连接器类型 ${connectorInfo.type} 不支持API接口查询`)
					apiList.value = []
					store.setApiList([])
					return
				}

				// 获取API接口列表
				const res = await dataConnectorApi.apisWithMeta({ id: store.formData.dataConnectorId })
				apiList.value = res || []
				store.setApiList(apiList.value)
			}
		} catch (error) {
			console.error('获取API接口列表失败:', error)
			// 如果是连接器类型不支持的错误，清空列表而不显示错误
			if (error.message && error.message.includes('该连接器类型不支持API接口查询')) {
				apiList.value = []
				store.setApiList([])
			}
		}
	}

	// 处理API选择变化
	const handleApiChange = (apiPath) => {
		const selectedApi = apiList.value.find((api) => api.apiPath === apiPath)
		if (selectedApi) {
			store.setApiPath(apiPath)
			store.setApiMethod('GET')
			// 清空之前的响应数据
			responseData.value = null
		}
	}

	// 获取请求方法的颜色
	const getMethodColor = (method) => {
		const colors = {
			GET: 'green',
			POST: 'blue',
			PUT: 'orange',
			DELETE: 'red',
			PATCH: 'purple'
		}
		return colors[method] || 'green'
	}

	// 自定义过滤函数
	const filterOption = (input, option) => {
		if (!input) return true
		const searchText = input.toLowerCase()
		const api = apiList.value.find((api) => api.apiPath === option.value)
		if (!api) return false

		// 搜索API路径、方法和描述
		const apiPath = (api.apiPath || '').toLowerCase()
		const apiMethod = (api.method || '').toLowerCase()
		const apiDescription = (api.apiDescription || '').toLowerCase()

		return apiPath.includes(searchText) || apiMethod.includes(searchText) || apiDescription.includes(searchText)
	}

	// 保存数据集配置
	const saveConfig = async () => {
		if (apiSaveActionsRef.value) {
			await apiSaveActionsRef.value.saveConfig()
		}
	}

	// 获取配置
	const getConfig = () => {
		if (!store.formData.itemConfig.apiPath) {
			return null
		}
		return {
			apiPath: store.formData.itemConfig.apiPath,
			apiMethod: 'GET',
			apiParams: store.formData.itemConfig.apiParams,
			selectedColumns: store.formData.itemConfig.selectedColumns,
			formatConfig: store.formData.itemConfig.formatConfig
		}
	}

	// 监听API选择变化
	watch(
		() => store.formData.itemConfig.apiPath,
		(newApiPath) => {
			if (newApiPath) {
				responseData.value = null
			}
		}
	)

	defineExpose({
		onOpen,
		getConfig,
		sendRequest,
		saveConfig
	})
</script>

<template>
	<div class="api-debugger">
		<!-- 请求配置区域 -->
		<div class="request-section">
			<div class="request-header">
				<div class="request-line">
					<div class="url-input">
						<a-select
							:filter-option="filterOption"
							:loading="!apiList.length"
							:value="store.formData.itemConfig.apiPath"
							class="w-full"
							placeholder="请选择API接口进行调试"
							show-search
							size="large"
							@change="handleApiChange"
						>
							<a-select-option
								v-for="api in apiList"
								:key="api.apiPath"
								:label="`${api.method} ${api.apiPath}`"
								:value="api.apiPath"
							>
								<div class="api-option-content">
									<div class="api-method-path">
										<a-tag :color="getMethodColor(api.method)" size="small">
											{{ api.method || 'GET' }}
										</a-tag>
										<span class="api-path">{{ api.apiPath }}</span>
									</div>
									<div v-if="api.apiDescription" class="api-description">
										{{ api.apiDescription }}
									</div>
								</div>
							</a-select-option>
						</a-select>
					</div>
					<div class="action-buttons">
						<a-button
							:disabled="!store.formData.itemConfig.apiPath"
							:loading="loading"
							size="large"
							type="primary"
							@click="sendRequest"
						>
							<send-outlined />
							发送
						</a-button>
						<ApiSaveActions ref="apiSaveActionsRef" @loadData="emit('loadData')" />
					</div>
				</div>
			</div>

			<!-- 参数配置面板 -->
			<div v-show="showParamsPanel" class="params-panel">
				<div class="params-header">
					<div class="params-title">
						<span>请求参数</span>
						<a-button size="small" type="text" @click="showParamsPanel = !showParamsPanel">
							<setting-outlined />
						</a-button>
					</div>
				</div>
				<div class="params-content">
					<api-debug-parameter-form @change="() => {}" />
				</div>
			</div>
		</div>

		<!-- 响应区域 -->
		<ApiResponseViewer
			:loading="loading"
			:response-data="responseData"
			:response-size="responseSize"
			:response-time="responseTime"
		/>
	</div>
</template>

<style scoped>
	.api-debugger {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background: #f5f5f5;
	}

	.request-section {
		background: #fff;
		border-bottom: 1px solid #e8e8e8;
	}

	.request-header {
		padding: 16px 20px;
		border-bottom: 1px solid #f0f0f0;
	}

	.request-line {
		display: flex;
		align-items: center;
		gap: 12px;
	}

	.method-tag {
		flex-shrink: 0;
	}

	.url-input {
		flex: 1;
	}

	.action-buttons {
		flex-shrink: 0;
		display: flex;
		gap: 8px;
	}

	.api-option-content {
		display: flex;
		flex-direction: column;
		gap: 4px;
	}

	.api-method-path {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.api-path {
		font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
		font-size: 13px;
		color: #262626;
	}

	.api-description {
		font-size: 12px;
		color: #8c8c8c;
		margin-left: 24px;
	}

	.params-panel {
		border-top: 1px solid #f0f0f0;
	}

	.params-header {
		padding: 12px 20px;
		background: #fafafa;
		border-bottom: 1px solid #f0f0f0;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.params-title {
		display: flex;
		align-items: center;
		gap: 8px;
		font-weight: 600;
		color: #262626;
	}

	.params-content {
		padding: 20px;
	}

	/* 响应式设计 */
	@media (max-width: 768px) {
		.request-line {
			flex-direction: column;
			gap: 8px;
		}

		.method-tag,
		.action-buttons {
			width: 100%;
		}

		.action-buttons {
			flex-direction: column;
		}

		.params-content {
			padding: 12px;
		}
	}
</style>
